from django.conf import settings
from django.core.files.storage import Storage
from django.utils.deconstruct import deconstructible
from qiniu import Auth, put_data

# import os
#
# QINIU_ACCESS_KEY = "vPeEYFHDnLu5smU7bMdMOYk5SvqctSYp1dp5e3fF"
# QINIU_SECRET_KEY = "83IOvlUi22S7j6OmN1UthuzODwYnDzB4_beNw_rh"
# QINIU_BUCKET_NAME = "mlh-guangzongyaozu11"
# QINIU_BUCKET_DOMAIN = "pjick4hrd.bkt.clouddn.com"
#
# QIUNIU_SECURE_URL = False  # 使用http
#
# PREFIX_URL = 'http://'  # 云存储前缀
#
# MEDIA_URL = PREFIX_URL + QINIU_BUCKET_DOMAIN + '/media/'
#
# MEDIA_ROOT = os.path.join(BASE_DIR, 'media')
#
# DEFAULT_FILE_STORAGE = 'qiniustorage.backends.QiniuMediaStorage'


@deconstructible
class QiNiuStorage(Storage):
    def _open(self, name, model='rb'):
        """不用打开，代码省略"""
        pass

    def _save(self, name, content):
        if name is None:
            name = content.name
        try:
            print('---------------------')
            q = Auth(settings.QINIU_ACCESS_KEY, settings.QINIU_SECRET_KEY)
            token = q.upload_token(settings.QINIU_BUCKET_NAME)
            print(token)
            ret, info = put_data(token, None, content.read())
            print(ret)
            print(info)
            print(ret, info)
        except Exception as e:

            print(type(e))
            print(e)
            print('---------------------')
            raise e

        if info.status_code != 200:
            raise Exception("上传图片失败")

        return settings.QINIU_BUCKET_DOMAIN + ret['key']

    def url(self, name):
        return name

    def exists(self, name):
        """七牛云自动解决文件重名问题"""
        return False

# if __name__ == '__main__':
#     file = input('请输入文件路径')
#     with open(file, 'rb') as f:
#         QiNiuStorage._save(f.read())
